package com.example.librarymanagementproject2.Common.config;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.scheduling.annotation.Async;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @ClassName EsConfig
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/24 8:34
 * @Version 1.0
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class EsConfig {
    private final ElasticsearchOperations elasticsearchOperations;
    /**
     * 注入所有 document 类
     */
    private final List<Class<?>> documentClass;

    /**
     * @author: kx
     * @date: 2025/10/24 8:37
     * @description: 触发异步创建
    */
    @PostConstruct
    public void triggerAsyncIndexCreation() {
        documentClasses();
        createAllIndexesAsync();
    }

    /**
     * @author: kx
     * @date: 2025/10/24 8:43
     * @description: 扫描指定包下带有 @Document 注解的类并存储到集合中
    */
    public void documentClasses() {
        // 创建 Reflections 对象,并指定扫描包路径
        Reflections reflections = new Reflections("com.example.librarymanagementproject2.model.document");
        // 获取所有带有 Document 注解的类
        Set<Class<?>> documentClasses = reflections.getTypesAnnotatedWith(Document.class);
        // 添加到 documentClass 列表中
        documentClass.addAll(documentClasses);
    }
    /**
     * @author: kx
     * @date: 2025/10/24 8:38
     * @return java.util.concurrent.CompletableFuture<java.lang.Void>
     * @description: 异步创建所有索引
    */
    @Async
    public CompletableFuture<Void> createAllIndexesAsync() {
        try {
            for (Class<?> documentClass : documentClass) {
                // 跳过没有 @Document 注解的类
                if (!documentClass.isAnnotationPresent(Document.class)) {
                    continue;
                }

                // 判断索引是否存在
                if (!elasticsearchOperations.indexOps(documentClass).exists()) {
                    // 创建索引
                    elasticsearchOperations.indexOps(documentClass).create();
                    // 创建映射
                    elasticsearchOperations.indexOps(documentClass).putMapping();
                }
            }
        } catch (Exception e) {
            log.error("创建索引失败: {}", e.getMessage());
        }
        // 返回一个已完成的 Future 对象
        return CompletableFuture.completedFuture(null);
    }
}
